package com.sike.netty.im.client.handler;

import com.sike.netty.im.client.ClientConnectRunner;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 重连 handler
 *
 * @author chenssy
 * @date 2023/09/26
 */
@Slf4j
public class ReconnectHandler extends ChannelInboundHandlerAdapter {
    private ClientConnectRunner clientConnectRunner;

    public ReconnectHandler(ClientConnectRunner clientConnectRunner) {
        this.clientConnectRunner = clientConnectRunner;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("{}，连接成功..",ctx.channel());
        ctx.fireChannelActive();
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.error("{}，失去连接，开始尝试重连",ctx.channel());
        ctx.executor().schedule(() -> {
            clientConnectRunner.connect();
        },5, TimeUnit.SECONDS);
    }
}
